<template>
  <div class="community-container">
    <!-- 页面标题 -->
    <div class="page-header">
      <h1>社区</h1>
      <p>浏览和搜索所有帖子</p>
    </div>

    <!-- 搜索区域 -->
    <div class="search-section">
      <el-row :gutter="20">
        <el-col :span="8">
          <el-input
            v-model="searchForm.username"
            placeholder="按用户名搜索"
            prefix-icon="el-icon-user"
            clearable
            @clear="handleSearch"
            @keyup.enter="handleSearch"
          />
        </el-col>
        <el-col :span="8">
          <el-input
            v-model="searchForm.title"
            placeholder="按标题搜索"
            prefix-icon="el-icon-document"
            clearable
            @clear="handleSearch"
            @keyup.enter="handleSearch"
          />
        </el-col>
        <el-col :span="8">
          <el-button type="primary" @click="handleSearch" icon="el-icon-search">
            搜索
          </el-button>
          <el-button @click="resetSearch" icon="el-icon-refresh">
            重置
          </el-button>
        </el-col>
      </el-row>
    </div>

    <!-- 帖子列表 -->
    <div class="posts-section" v-loading="loading">
      <el-card class="post-card" v-for="post in posts" :key="post.postId" shadow="hover">
        <div class="post-content">
          <!-- 帖子标题 -->
          <div class="post-header">
            <h3 class="post-title" @click="viewPostDetail(post.postId)">
              {{ post.title }}
            </h3>
            <div>
              <el-tag v-if="post.tag" type="info" size="small">
                {{ post.tag }}
              </el-tag>
              <el-button 
                type="text" 
                @click.stop="toggleFavorite(post)"
                :icon="post.isFavorite ? 'el-icon-star-on' : 'el-icon-star-off'"
                :style="{color: post.isFavorite ? '#ffc107' : '#909399'}"
                class="favorite-btn"
              >
                {{ post.isFavorite ? '已收藏' : '收藏' }}
              </el-button>
            </div>
          </div>

          <!-- 帖子信息 -->
          <div class="post-info">
            <div class="post-meta">
              <span class="meta-item">
                <i class="el-icon-user"></i>
                {{ post.username }}
              </span>
              <span class="meta-item">
                <i class="el-icon-view"></i>
                {{ post.viewCount || 0 }} 浏览
              </span>
              <span class="meta-item">
                <i class="el-icon-chat-line-square"></i>
                {{ post.commentCount || 0 }} 评论
              </span>
              <span class="meta-item">
                <i class="el-icon-star-off"></i>
                {{ post.favoriteCount || 0 }} 收藏
              </span>
            </div>
            
            <div class="post-time">
              <div class="time-item">
                <span class="time-label">发布：</span>
                <span>{{ formatDate(post.createdAt) }}</span>
              </div>
              <div class="time-item" v-if="post.updatedAt !== post.createdAt">
                <span class="time-label">更新：</span>
                <span>{{ formatDate(post.updatedAt) }}</span>
              </div>
            </div>
          </div>

          <!-- 查看详情按钮 -->
          <div class="post-actions">
            <el-button type="text" @click="viewPostDetail(post.postId)">
              查看详情 <i class="el-icon-arrow-right"></i>
            </el-button>
          </div>
        </div>
      </el-card>

      <!-- 空状态 -->
      <el-empty v-if="!loading && posts.length === 0" description="暂无帖子"></el-empty>
    </div>

    <!-- 分页 -->
    <div class="pagination-section" v-if="total > 0">
      <el-pagination
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="currentPage"
        :page-sizes="[5, 10, 20, 50]"
        :page-size="pageSize"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
      />
    </div>
  </div>
</template>

<script>
import { ref, reactive, onMounted } from 'vue'
import { useRouter } from 'vue-router'
import axios from 'axios'
import { ElMessage } from 'element-plus'
import { useUserStore } from '@/store/user'

export default {
  name: 'Community',
  setup() {
    const router = useRouter()
    const userStore = useUserStore()
    
    // 响应式数据
    const loading = ref(false)
    const posts = ref([])
    const currentPage = ref(1)
    const pageSize = ref(10)
    const total = ref(0)
    
    // 搜索表单
    const searchForm = reactive({
      username: '',
      title: ''
    })

    // API 基础URL
    const API_BASE_URL = 'http://localhost:8081'

    // 格式化日期
    const formatDate = (dateString) => {
      if (!dateString) return ''
      const date = new Date(dateString)
      return date.toLocaleDateString('zh-CN', {
        year: 'numeric',
        month: '2-digit',
        day: '2-digit',
        hour: '2-digit',
        minute: '2-digit'
      })
    }

    // 获取帖子列表
    const fetchPosts = async () => {
      loading.value = true
      try {
        let url = `${API_BASE_URL}/community/posts`
        const params = {
          pageNum: currentPage.value,
          pageSize: pageSize.value
        }

        // 根据搜索条件选择不同的接口
        if (searchForm.username) {
          url = `${API_BASE_URL}/community/posts/username`
          params.username = searchForm.username
        } else if (searchForm.title) {
          url = `${API_BASE_URL}/community/posts/title`
          params.title = searchForm.title
        }

        const response = await axios.get(url, { params })
        const pageInfo = response.data
        
        // 添加isFavorite字段，初始值为false
        posts.value = (pageInfo.list || []).map(post => ({
          ...post,
          isFavorite: post.is_favorite === 1
        }))
        total.value = pageInfo.total || 0
        currentPage.value = pageInfo.pageNum || 1
        pageSize.value = pageInfo.pageSize || 10
        
      } catch (error) {
        console.error('获取帖子列表失败:', error)
        ElMessage.error('获取帖子列表失败')
      } finally {
        loading.value = false
      }
    }

    // 切换收藏状态
    const toggleFavorite = async (post) => {
      if (!userStore.userId) {
        ElMessage.warning('请先登录后再收藏')
        return
      }

      // 保存原始状态用于回滚
      const originalState = post.isFavorite
      const originalCount = post.favoriteCount || 0
      
      // 立即更新UI状态（乐观更新）
      post.isFavorite = !originalState
      post.favoriteCount = originalState ? originalCount - 1 : originalCount + 1

      try {
        const favoriteVO = {
          post_id: post.postId,
          user_id: userStore.userId,
          is_favorite: !originalState
        }

        const url = originalState 
          ? `${API_BASE_URL}/api/user/post/favorite/remove`
          : `${API_BASE_URL}/api/user/post/favorite/add`

        const response = await axios.post(url, favoriteVO)
        
        if (response.data !== "收藏成功" && response.data !== "取消收藏成功") {
          // 如果后端返回不成功，回滚状态
          post.isFavorite = originalState
          post.favoriteCount = originalCount
          ElMessage.error(response.data || '操作失败')
          return
        }

        ElMessage.success(response.data)
        
      } catch (error) {
        console.error('操作收藏失败:', error)
        // 出错时回滚状态
        post.isFavorite = originalState
        post.favoriteCount = originalCount
        
        if (error.response?.data?.message?.includes("Duplicate entry")) {
          ElMessage.error('您已经收藏过这个帖子了')
        } else {
          ElMessage.error('操作收藏失败: ' + (error.response?.data?.message || error.message))
        }
      }
    }

    // 处理搜索
    const handleSearch = () => {
      currentPage.value = 1
      fetchPosts()
    }

    // 重置搜索
    const resetSearch = () => {
      searchForm.username = ''
      searchForm.title = ''
      currentPage.value = 1
      fetchPosts()
    }

    // 页面大小改变
    const handleSizeChange = (newSize) => {
      pageSize.value = newSize
      currentPage.value = 1
      fetchPosts()
    }

    // 当前页改变
    const handleCurrentChange = (newPage) => {
      currentPage.value = newPage
      fetchPosts()
    }

    // 查看帖子详情
    const viewPostDetail = (postId) => {
      router.push(`/post-detail/${postId}`)
    }

    // 页面加载时获取数据
    onMounted(() => {
      fetchPosts()
    })

    return {
      loading,
      posts,
      currentPage,
      pageSize,
      total,
      searchForm,
      formatDate,
      toggleFavorite,
      handleSearch,
      resetSearch,
      handleSizeChange,
      handleCurrentChange,
      viewPostDetail
    }
  }
}
</script>

<style scoped>
.community-container {
  padding: 20px;
  max-width: 1200px;
  margin: 0 auto;
}

.page-header {
  text-align: center;
  margin-bottom: 30px;
}

.page-header h1 {
  color: #303133;
  margin-bottom: 10px;
}

.page-header p {
  color: #606266;
  font-size: 14px;
}

.search-section {
  background: white;
  padding: 20px;
  border-radius: 8px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
  margin-bottom: 20px;
}

.posts-section {
  min-height: 400px;
}

.post-card {
  margin-bottom: 20px;
  cursor: pointer;
  transition: all 0.3s ease;
}

.post-card:hover {
  transform: translateY(-2px);
}

.post-content {
  padding: 10px;
}

.post-header {
  display: flex;
  justify-content: space-between;
  align-items: flex-start;
  margin-bottom: 15px;
}

.post-title {
  color: #409EFF;
  font-size: 18px;
  font-weight: 600;
  margin: 0;
  cursor: pointer;
  flex: 1;
  margin-right: 10px;
  line-height: 1.4;
}

.post-title:hover {
  text-decoration: underline;
}

.post-info {
  display: flex;
  justify-content: space-between;
  align-items: flex-end;
  margin-bottom: 15px;
  flex-wrap: wrap;
  gap: 10px;
}

.post-meta {
  display: flex;
  flex-wrap: wrap;
  gap: 15px;
}

.meta-item {
  color: #909399;
  font-size: 14px;
  display: flex;
  align-items: center;
  gap: 4px;
}

.meta-item i {
  font-size: 16px;
}

.post-time {
  display: flex;
  flex-direction: column;
  gap: 4px;
  align-items: flex-end;
}

.time-item {
  font-size: 12px;
  color: #C0C4CC;
}

.time-label {
  font-weight: 500;
}

.post-actions {
  text-align: right;
  border-top: 1px solid #EBEEF5;
  padding-top: 10px;
}

.pagination-section {
  display: flex;
  justify-content: center;
  margin-top: 30px;
  padding: 20px;
}

.favorite-btn {
  padding: 0;
  margin-left: 10px;
  font-size: 16px;
}

.favorite-btn i {
  margin-right: 4px;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .community-container {
    padding: 10px;
  }
  
  .post-info {
    flex-direction: column;
    align-items: flex-start;
  }
  
  .post-time {
    align-items: flex-start;
    align-self: stretch;
  }
  
  .search-section .el-row {
    flex-direction: column;
  }
  
  .search-section .el-col {
    width: 100%;
    margin-bottom: 10px;
  }
}
</style>